package com.shop.controller;
import com.shop.dao.LoginDao;
import com.shop.entity.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

/**
 * 实现用户登录和注册
 * 密码加密
 */
@RestController
public class LoginController {

    @Resource
    private LoginDao ld;
    //private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    @Autowired
    private BCryptPasswordEncoder encoder;


    @PostMapping("/login")
    public LoginResponse login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User existingUser = ld.getUserByUsername(username);
        if (existingUser == null || !encoder.matches(password, existingUser.getPassword())) {
            return new LoginResponse(false, "用户名不存在或密码错误");
        }
        return new LoginResponse(true, "登录成功");
    }

    @PostMapping("/register")
    public RegisterResponse register(@RequestParam("username") String username,
                                     @RequestParam("password") String password,
                                     @RequestParam("role") String role) {
        if (ld.checkUsernameExists(username)) {
            return new RegisterResponse(false, "用户名已存在");
        }
        // 加密密码
        String encryptedPassword = encoder.encode(password);
        int result = ld.register(username, encryptedPassword, role);
        if (result == 0) {
            return new RegisterResponse(false, "用户名已存在或注册过程出错");
        }
        return new RegisterResponse(true, "注册成功");
    }

}
